import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/common/state/common_net_status.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/opt_input_field.dart';
import 'package:casdon/common/widget/resend_code_button.dart';
import 'package:casdon/core/auth/auth_storage.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/modules/home/application/notification/tuya_auth_notifier.dart';
import 'package:casdon/modules/login/application/notifier/login_apple_notifier.dart';
import 'package:casdon/modules/login/application/notifier/login_del_account_notifier.dart';
import 'package:casdon/modules/login/application/notifier/login_type_notifier.dart';
import 'package:casdon/modules/login/application/notifier/login_update_pwd_notifier.dart';
import 'package:casdon/modules/login/application/notifier/login_wechat_notifier.dart';
import 'package:casdon/modules/login/application/notifier/regist_account_notifier.dart';
import 'package:casdon/modules/login/domain/states/del_account_state.dart';
import 'package:casdon/modules/login/domain/states/login_apple_state.dart';
import 'package:casdon/modules/login/domain/states/login_code_state.dart';
import 'package:casdon/modules/login/domain/states/login_wechat_state.dart';
import 'package:casdon/modules/login/domain/states/regist_account_state.dart';
import 'package:casdon/modules/login/domain/states/update_pwd_state.dart';
import 'package:casdon/modules/login/providers/login_apple_provider.dart';
import 'package:casdon/modules/login/providers/login_code_provider.dart';
import 'package:casdon/modules/login/providers/login_provider.dart';
import 'package:casdon/modules/login/providers/login_wechat_provider.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

@RoutePage()
class CodeInputScreen extends ConsumerStatefulWidget {
  final String screenId;
  final String account;
  final bool showBackArrow;

  const CodeInputScreen({
    super.key,
    required this.account,
    this.showBackArrow = false,
    this.screenId = 'CodeInputScreen',
  });

  @override
  ConsumerState<CodeInputScreen> createState() => _CodeInputScreenState();
}

class _CodeInputScreenState extends ConsumerState<CodeInputScreen> {
  late final TextEditingController _codeEditingController;
  late final ProviderSubscription<LoginCodeState> _codeSubscription;
  late final ProviderSubscription<LoginAppleState> _appleSubscription;
  late final ProviderSubscription<LoginWechatState> _wechatSubscription;
  late final ProviderSubscription<UpdatePwdState> _updateSubscription;
  late final ProviderSubscription<DelAccountState> _delAccountSubscription;
  late final ProviderSubscription<RegistAccountState>
  _registerAccountSubscription;

  @override
  void initState() {
    super.initState();
    _codeEditingController = ref.read(
      editingControllerProvider(widget.screenId),
    );
    _setupListeners();
  }

  @override
  void dispose() {
    _codeEditingController.dispose();
    _codeSubscription.close();
    _appleSubscription.close();
    _wechatSubscription.close();
    _updateSubscription.close();
    _delAccountSubscription.close();
    _registerAccountSubscription.close();
    super.dispose();
  }

  void _setupListeners() {
    _codeSubscription = ref.listenManual<LoginCodeState>(
      loginCodeProvider,
      (pri, next) => _handleLoginCodeState(pri, next),
    );

    _appleSubscription = ref.listenManual<LoginAppleState>(
      loginAppleProvider,
      (pri, next) => _handleLoginAppleState(pri, next),
    );

    _wechatSubscription = ref.listenManual<LoginWechatState>(
      loginWechatProvider,
      (pri, next) => _handleLoginWechatState(pri, next),
    );

    _updateSubscription = ref.listenManual<UpdatePwdState>(
      loginModifyPwdNotifierProvider,
      (pri, next) => _handleUpdatePwdState(pri, next),
    );

    _delAccountSubscription = ref.listenManual<DelAccountState>(
      loginDelAccountNotifierProvider,
      (pri, next) => _handleDelAccountState(pri, next),
    );

    _registerAccountSubscription = ref.listenManual<RegistAccountState>(
      registerAccountProvider,
      (pri, next) => _handleRegisterAccountState(pri, next),
    );
  }

  @override
  Widget build(BuildContext context) {
    final int gapSize = 24;

    return Scaffold(
      resizeToAvoidBottomInset: true,
      appBar: widget.showBackArrow ? CommonAppBar(title: '') : null,
      body: SafeArea(
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: gapSize.h),
          child: SingleChildScrollView(
            padding: EdgeInsets.only(
              bottom: MediaQuery.of(context).viewInsets.bottom,
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                SizedBox(height: widget.showBackArrow ? 24.0.h : 72.h),
                Text(
                  '输入验证码',
                  style: Theme.of(context).textTheme.displayLarge?.copyWith(
                    color: context.customColorThemeNonNull.headLargeTitle,
                  ),
                ),
                SizedBox(height: 74.0.h),
                OTPInputField(
                  controller: _codeEditingController,
                  onCompleted: (code) {
                    _verifyCode(code);
                  },
                ),
                SizedBox(height: 16.0.h),
                Row(
                  children: [
                    Expanded(
                      child: Text(
                        '已发送至 ${widget.account}',
                        style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                          color: context.customColorThemeNonNull.textColor3,
                        ),
                        overflow: TextOverflow.ellipsis,
                        maxLines: 1,
                      ),
                    ),
                    ConstrainedBox(
                      constraints: const BoxConstraints(minWidth: 50),
                      child: ResendCodeButton(onResend: () => _resendCode()),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void _resendCode() {
    _codeEditingController.clear();
    final type = ref.read(loginTypeProvider);

    switch (type) {
      case LoginType.optCode:
        ref
            .read(loginCodeProvider.notifier)
            .sendCode(source: SendCodeSource.codePage);
        break;
      case LoginType.wechat:
        ref
            .read(loginWechatProvider.notifier)
            .sendCode(source: SendCodeSource.codePage);
        break;
      case LoginType.apple:
        ref
            .read(loginAppleProvider.notifier)
            .sendCode(source: SendCodeSource.codePage);
        break;
      case LoginType.updatePwd:
        ref
            .read(loginModifyPwdNotifierProvider.notifier)
            .sendCode(source: SendCodeSource.codePage);
        break;
      case LoginType.delAccount:
        ref
            .read(loginDelAccountNotifierProvider.notifier)
            .sendCode(source: SendCodeSource.codePage);
        break;

      case LoginType.register:
        ref
            .read(registerAccountProvider.notifier)
            .sendCode(source: SendCodeSource.codePage);
        break;
      default:
        break;
    }
  }

  void _verifyCode(String code) {
    final type = ref.read(loginTypeProvider);

    switch (type) {
      case LoginType.optCode:
        ref.read(loginCodeProvider.notifier).updateCode(code);
        ref.read(loginCodeProvider.notifier).login();
        break;
      case LoginType.wechat:
        ref.read(loginWechatProvider.notifier).updateCode(code);
        ref.read(loginWechatProvider.notifier).verifyCode();
        break;
      case LoginType.apple:
        ref.read(loginAppleProvider.notifier).updateCode(code);
        ref.read(loginAppleProvider.notifier).verifyCode();
        break;
      case LoginType.updatePwd:
        ref.read(loginModifyPwdNotifierProvider.notifier).updateCode(code);
        ref.read(loginModifyPwdNotifierProvider.notifier).verifyCode();
        break;
      case LoginType.delAccount:
        ref.read(loginDelAccountNotifierProvider.notifier).updateCode(code);
        ref.read(loginDelAccountNotifierProvider.notifier).verifyCode();
        break;
      case LoginType.register:
        ref.read(registerAccountProvider.notifier).updateCode(code);
        ref.read(registerAccountProvider.notifier).verifyCode();
        break;
      default:
        break;
    }
  }

  void _handleLoginCodeState(LoginCodeState? previous, LoginCodeState next) {
    if (!mounted) return;
    final notifier = ref.read(loginCodeProvider.notifier);
    if (notifier.step == LoginCodeStep.sendCode) {
      if (next.source == SendCodeSource.codePage) {
        if (next.status == CommonNetStatus.success) {
          ToastUtil.show(next.message ?? "发送验证码成功");
        } else if (next.status == CommonNetStatus.failure) {
          ToastUtil.show(next.message ?? "发送验证码失败");
        }
      }
    }
    if (notifier.step == LoginCodeStep.login) {
      if (next.status == CommonNetStatus.success) {
        ToastUtil.show(next.message ?? "登录成功");

        context.router.replaceAll(const [TabRoute()]);
      } else if (next.status == CommonNetStatus.failure) {
        ToastUtil.show(next.message ?? "登录失败");
      }
    }
  }

  void _handleLoginWechatState(
    LoginWechatState? previous,
    LoginWechatState next,
  ) {
    if (!mounted) return;
    final wxNotifier = ref.read(loginWechatProvider.notifier);
    if (wxNotifier.step == WeChatLoginStep.sendCode) {
      if (next.source == SendCodeSource.codePage) {
        if (next.status == CommonNetStatus.success) {
          ToastUtil.show(next.message ?? "发送验证码成功");
        } else if (next.status == CommonNetStatus.failure) {
          ToastUtil.show(next.message ?? "发送验证码失败");
        }
      }
      return;
    }
    if (wxNotifier.step == WeChatLoginStep.verifyCode) {
      if (next.status == CommonNetStatus.success) {
        ToastUtil.show(next.message ?? "验证码正确");
        wxNotifier.login();
      } else if (next.status == CommonNetStatus.failure) {
        ToastUtil.show(next.message ?? "验证码错误");
      }
    }
    if (wxNotifier.step == WeChatLoginStep.afterbindingLogin) {
      if (next.status == CommonNetStatus.success) {
        ToastUtil.show(next.message ?? "绑定成功");

        context.router.replaceAll(const [TabRoute()]);
      } else if (next.status == CommonNetStatus.failure) {
        ToastUtil.show(next.message ?? "绑定失败");
      }
    }
  }

  void _handleLoginAppleState(LoginAppleState? previous, LoginAppleState next) {
    if (!mounted) return;
    final appleNotifier = ref.read(loginAppleProvider.notifier);
    if (appleNotifier.step == AppleLoginStep.sendCode) {
      if (next.status == CommonNetStatus.success) {
        ToastUtil.show(next.message ?? "发送验证码成功");
      } else if (next.status == CommonNetStatus.failure) {
        ToastUtil.show(next.message ?? "发送验证码失败");
      }
      return;
    }
    if (appleNotifier.step == AppleLoginStep.verifyCode) {
      if (next.status == CommonNetStatus.success) {
        ToastUtil.show(next.message ?? "验证码正确");
        appleNotifier.login();
      } else if (next.status == CommonNetStatus.failure) {
        ToastUtil.show(next.message ?? "验证码错误");
      }
    }
    if (appleNotifier.step == AppleLoginStep.afterbindingLogin) {
      if (next.status == CommonNetStatus.success) {
        ToastUtil.show(next.message ?? "绑定成功");
        context.router.replaceAll(const [TabRoute()]);
      } else if (next.status == CommonNetStatus.failure) {
        ToastUtil.show(next.message ?? "绑定失败");
      }
    }
  }

  void _handleUpdatePwdState(UpdatePwdState? previous, UpdatePwdState next) {
    if (!mounted) return;
    final notifier = ref.read(loginModifyPwdNotifierProvider.notifier);
    if (notifier.step == UpdatePwdtep.sendCode) {
      if (next.source == SendCodeSource.codePage) {
        if (next.status == CommonNetStatus.success) {
          ToastUtil.show(next.message ?? "发送验证码成功");
        } else if (next.status == CommonNetStatus.failure) {
          ToastUtil.show(next.message ?? "发送验证码失败");
        }
      }
    }
    if (notifier.step == UpdatePwdtep.verifyCode) {
      if (next.status == CommonNetStatus.success) {
        context.router.push(SetNewPwdRoute());
      } else if (next.status == CommonNetStatus.failure) {
        ToastUtil.show(next.message ?? "验证码错误");
      }
    }
  }

  void _handleDelAccountState(
    DelAccountState? previous,
    DelAccountState next,
  ) async {
    if (!mounted) return;
    final notifier = ref.read(loginDelAccountNotifierProvider.notifier);
    if (notifier.step == DelAccountStep.sendCode) {
      if (next.source == SendCodeSource.codePage) {
        if (next.status == CommonNetStatus.success) {
          ToastUtil.show(next.message ?? "发送验证码成功");
        } else if (next.status == CommonNetStatus.failure) {
          ToastUtil.show(next.message ?? "发送验证码失败");
        }
      }
    }
    if (notifier.step == DelAccountStep.verifyCode) {
      if (next.status == CommonNetStatus.success) {
        await notifier.delAccount();
      } else if (next.status == CommonNetStatus.failure) {
        ToastUtil.show(next.message ?? "验证码错误");
      }
    }
    if (notifier.step == DelAccountStep.delAccount) {
      if (next.status == CommonNetStatus.success) {
        if (mounted == false) return;
        await ref.read(tuyaLoginProvider.notifier).logOut();
        if (mounted == false) return;
        await ref.read(authStorageProvider.notifier).clear();
        if (mounted == false) return;

        context.router.replaceAll(const [AccountInputRoute()]);
      } else if (next.status == CommonNetStatus.failure) {
        ToastUtil.show(next.message ?? "注销账户失败");
      }
    }
  }

  void _handleRegisterAccountState(
    RegistAccountState? pri,
    RegistAccountState next,
  ) async {
    if (!mounted) return;
    final notifier = ref.read(registerAccountProvider.notifier);
    if (notifier.step == RegistAccountStep.sendCode) {
      if (next.source == SendCodeSource.codePage) {
        if (next.status == CommonNetStatus.success) {
          ToastUtil.show(next.message ?? "发送验证码成功");
        } else if (next.status == CommonNetStatus.failure) {
          ToastUtil.show(next.message ?? "发送验证码失败");
        }
      }
    }
    if (notifier.step == RegistAccountStep.verifyCode) {
      if (next.status == CommonNetStatus.success) {
        if (mounted) context.router.push(SetNewPwdRoute(title: "设置密码"));
      } else if (next.status == CommonNetStatus.failure) {
        ToastUtil.show(next.message ?? "验证码错误");
      }
    }
    // if (notifier.step == RegistAccountStep.register) {
    //   if (next.status == CommonNetStatus.success) {
    //     await notifier.register();
    //   } else if (next.status == CommonNetStatus.failure) {
    //     ToastUtil.show(next.message ?? "注册失败");
    //   }
    // }
  }
}
